import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import 'package:syria_sports/data/apiClient/apis_data.dart';
import 'package:collection/collection.dart'; // You have to add this manually, for some reason it cannot be added automatically
import 'package:syria_sports/data/controllers/subscriptions_controller.dart';
import 'package:syria_sports/presentation/subscriptions/subscriptions_page/models/subscription.dart';

import '../core/utils/validation_functions.dart';
import '../data/models/auth/user.dart';
import '../presentation/admin_home_tabs/cp_tab/models/home_model.dart';
import '../widgets/custom_text_form_field.dart';
FluffyGym? _selectedGym;
GymExercise? _selectedExercise;
String? _startDate;
String? _endDate;

class SubscriptionDialog extends StatefulWidget {
  final User user;
  const SubscriptionDialog({super.key, required this.user});

  @override
  State<SubscriptionDialog> createState() => _SubscriptionDialogState();
}

class _SubscriptionDialogState extends State<SubscriptionDialog> {
  TextEditingController startDateController = TextEditingController();
  TextEditingController endDateController = TextEditingController();


  @override
  void initState() {
    // TODO: implement initState

    _selectedGym = APISData.homeData.gyms.firstWhereOrNull((element) => element.gymId == _selectedGym?.gymId);
    _selectedExercise = _selectedGym?.exercises.firstWhereOrNull((element) => element.exerciseId == _selectedExercise?.exerciseId);

    endDateController.text= _endDate??'';
    startDateController.text= _startDate??DateTime.now().formatInput();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shadowColor: Colors.grey,
      elevation: 16,
      backgroundColor: Theme.of(context).colorScheme.secondary,
      title: const Text('إضافة اشتراك'),
      content: SizedBox(
        height: MediaQuery.of(context).size.height/2.5,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              DropdownButton<FluffyGym>(
                value: _selectedGym,
                dropdownColor: Colors.black,
                isExpanded: true,
                hint: Text('اختر نادي',style: theme.textTheme.titleSmall,),
                onChanged: (value) {
                  setState(() {
                    _selectedGym = value;
                    _selectedExercise = null;
                  });
                },
                items: List.generate(APISData.homeData.gyms.length, (index) => DropdownMenuItem(
                  value: APISData.homeData.gyms[index],
                  child: Text(APISData.homeData.gyms[index].name,style: theme.textTheme.titleSmall!.copyWith(color: Colors.orange),),
                  ),
                ),
              ),
              const SizedBox(height: 8),
              DropdownButton<GymExercise>(
                value: _selectedExercise,
                dropdownColor: Colors.black,
                isExpanded: true,
                hint: Text('اختر التمرين',style: theme.textTheme.titleSmall,),
                onChanged: (value) {
                  setState(() {
                    _selectedExercise = value;
                  });
                },
                items:(_selectedGym==null)?[]:List.generate(_selectedGym!.exercises.length, (index) =>
                    DropdownMenuItem(
                value: _selectedGym!.exercises[index],
                child: Text(_selectedGym!.exercises[index].name,style: theme.textTheme.titleSmall!.copyWith(color: Colors.orange),),
              ),
    ),
              ),
              const SizedBox(height: 8),
              CustomTextFormField(
                  controller: startDateController,
                  onFieldSubmitted: (value){
                    FocusScope.of(context).unfocus();
                  },
                  hintText: "ادخل تاريخ البدء (31-12-2000)",
                  title: 'تاريخ البداية',
                  textInputAction: TextInputAction.next,
                  textInputType: TextInputType.datetime,
                  fillColor: Theme.of(context).colorScheme.secondary,
                  prefix: Container(
                      margin: EdgeInsets.fromLTRB(
                          16.h, 12.v, 10.h, 12.v),
                      child: InkWell(
                        onTap: (){
                          selectDate(context ,true);
                        },
                        child: CustomImageView(
                            imagePath: ImageConstant.icCalendar,
                            color: Colors.grey,
                            height: 24.adaptSize,
                            width: 24.adaptSize),
                      )),
                  prefixConstraints: BoxConstraints(maxHeight: 48.v,maxWidth: 48.h),
                  validator: (value) {
                    if (value != null && value.isNotEmpty && !isValidDate(value)) {
                      return 'الرجاء ادخال تاريخ صالح(سنة-شهر-يوم)';
                    }
                    return null;
                  },
                  obscureText: false,
                  contentPadding: EdgeInsets.only(
                      top: 15.v, right: 30.h, bottom: 15.v)),
              const SizedBox(height: 16),
              CustomTextFormField(
                  controller: endDateController,
                  onFieldSubmitted: (value){
                    //FocusScope.of(context).unfocus();
                  },
                  hintText: "ادخل تاريخ الانتهاء (31-12-2000)",
                  title: 'تاريخ الانتهاء',
                  textInputAction: TextInputAction.next,
                  textInputType: TextInputType.datetime,
                  fillColor: Theme.of(context).colorScheme.secondary,
                  prefix: Container(
                      margin: EdgeInsets.fromLTRB(
                          16.h, 12.v, 10.h, 12.v),
                      child: InkWell(
                        onTap: (){
                          selectDate(context ,false);
                        },
                        child: CustomImageView(
                            imagePath: ImageConstant.icCalendar,
                            color: Colors.grey,
                            height: 24.adaptSize,
                            width: 24.adaptSize),
                      )),
                  prefixConstraints: BoxConstraints(maxHeight: 48.v,maxWidth: 48.h),
                  validator: (value) {
                    if (value != null && value.isNotEmpty && !isValidDate(value)) {
                      return 'الرجاء ادخال تاريخ صالح(سنة-شهر-يوم)';
                    }
                    return null;
                  },
                  obscureText: false,
                  contentPadding: EdgeInsets.only(
                      top: 15.v, right: 30.h, bottom: 15.v)),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            // قم بتنفيذ الإجراء عند الضغط على زر الإضافة
            _startDate = startDateController.text;
            _endDate = endDateController.text;
            if(DateTime.tryParse(_startDate??'')== null || DateTime.tryParse(_endDate??'')== null){
              showErrorMessage(message: 'الرجاء تحديد تاريخ صالح');
              return;
            }
            if(_selectedExercise == null){
              showErrorMessage(message: 'الرجاء تحديد تمرين');
              return;
            }
            Subscription newSubscription  = Subscription(
              subscriptionId: '-1',
              userId:widget.user.userId!,
              startDate: DateTime.parse(_startDate!),
              endDate: DateTime.parse(_endDate!),
              exerciseId: _selectedExercise!.exerciseId,
              );
            addSubscription(newSubscription);
            Navigator.of(context).pop(); // إغلاق الديالوج

          },
          child: Text('إضافة',style :theme.textTheme.titleMedium),
        ),
        TextButton(
          onPressed: () {
            Navigator.of(context).pop(); // إغلاق الديالوج
          },
          child: Text('رجوع',style :theme.textTheme.titleMedium),
        ),
      ],
    );
  }



  Future<void> selectDate(BuildContext context ,bool flag) async {
    final DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2020),
      lastDate: DateTime(3000),
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData(
            fontFamily: 'Tajawal',
            visualDensity: VisualDensity.standard,
            colorScheme: const ColorScheme.dark().copyWith(
              primary: Colors.red, // تحديد اليوم بلون أحمر
            ),
            textButtonTheme: TextButtonThemeData(
              style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
              ),
            ),
          ),
          child: child!,
        );
      },
    );

    if (pickedDate != null) {
      setState(() {
        String formattedDate = DateFormat('yyyy-MM-dd').format(pickedDate);
        if(flag) {
          startDateController.text = formattedDate;
        }else{
          endDateController.text = formattedDate;
        }
      });
    }

  }


  Future<void> addSubscription(Subscription subscription)async{

    SubscriptionsController.addSubscription(subscription).then((value){
      if(value!= null){
        showMessage(value.message);
      }

    }).catchError((e){
      showErrorMessage(message: 'عذراً حدث خطأ ما الرجاء إعادة المحاولة لاحقاً');
    });

  }

}

